package com.func.domain.strategy.service.rule.tree.impl;

import com.func.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.func.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import com.func.domain.strategy.repository.IStrategyRepository;
import com.func.domain.strategy.service.rule.tree.ILogicTreeNode;
import com.func.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import com.func.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @version 1.0
 * @className RuleLuckLogicTreeNode
 * @description 规则树节点-幸运奖规则
 * @author: func
 * @date 2025/2/28 21:20
 */

@Slf4j
@Component("rule_luck_award")
public class RuleLuckLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyRepository strategyRepository;

    /**
     * 兜底奖品
     * 101:1,100
     *
     * @param userId
     * @param strategyId
     * @param awardId     前面抽奖得到的奖品Id
     * @param ruleValue
     * @param endDateTime
     * @return
     */

    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {
        String[] ruleValueGroup = ruleValue.split(Constants.COLON);
        log.info("规则过滤-兜底奖品 : userId : {}, strategyId : {}, awardId : {}, ruleValue : {}", userId, strategyId, awardId, ruleValue);
        if (ruleValueGroup.length == 0) {
            log.error("规则过滤-兜底奖品 : 兜底奖品未配置警告 userId : {}, strategyId : {}, awardId : {}, ruleValue : {}", userId, strategyId, awardId, ruleValue);
            throw new RuntimeException("兜底奖品未配置" + ruleValue);
        }
        Integer luckAward = Integer.parseInt(ruleValueGroup[0]);
        String awardRuleValue = ruleValueGroup.length > 1 ? ruleValueGroup[1] : "";

        // 将奖品加入到延迟队列中, 数据库延迟更新发奖
        strategyRepository.awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder()
                .awardId(awardId)
                .strategyId(strategyId)
                .build());

        log.info("规则过滤-兜底奖品-接管 : userId : {}, strategyId : {}, awardId : {}, ruleValue : {}", userId, strategyId, awardId, ruleValue);
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                        .awardId(luckAward)
                        .awardRuleValue(awardRuleValue)
                        .build())
                .build();
    }
}
